package com.imtimmy.android.pda;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.imtimmy.android.pda.calendar.CalendarActivity;

public class pda extends Activity {
	private Context context = this;
	private Button btn_NewActivity;
	private ListView lv_Activities;

	private ArrayList<ActivityInfo> aInfos = Global.activityInfos;
	private ActivityItemAdapter listAdapter;

	private AlarmManager alarmManager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("create", "called");
		setContentView(R.layout.main);

		btn_NewActivity = (Button) findViewById(R.id.btn_New_main);
		lv_Activities = (ListView) findViewById(R.id.listView_ActivityList_main);
		listAdapter = new ActivityItemAdapter(this);
		btn_NewActivity.setOnClickListener(newActivityClick);
	}

	@Override
	protected void onResume() {

		super.onResume();
		if (aInfos == null){
			aInfos = new ArrayList<ActivityInfo>();
		}
		
		initDataFromDB(aInfos);
		
		listAdapter.AddData(aInfos);	
		lv_Activities.setAdapter(listAdapter);
		listAdapter.notifyDataSetChanged();
		registerForContextMenu(lv_Activities);

		lv_Activities.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent i = new Intent();
				i.setClass(parent.getContext(), ViewActivity.class);
				ActivityInfo aInfo = aInfos.get(position);
				Bundle bundle = Global.getBundle(aInfo);
				i.putExtras(bundle);
				startActivity(i);
			}
		});
		
		Intent intent = getIntent();
		long date = intent.getLongExtra("date", 0);
		if (date != 0) {
			int position = Global.getPostionByDate(date);
			if (position != -1)
				lv_Activities.setSelection(position);
		}
		// listAdapter.notifyDataSetChanged();
	}

	private OnClickListener newActivityClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(context, NewActivity.class);
			startActivityForResult(intent, Global.REQUEST_ID_NEWACTIVITY);

		}
	};

//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		Log.i("Result", "called");
//		if (requestCode == Global.REQUEST_ID_NEWACTIVITY) {
//			switch (resultCode) {
//			case RESULT_OK:
//				Bundle bundle = data.getExtras();
//				ActivityInfo aInfo = Global.getActivityInfo(bundle);
//				insertData(aInfo);
//				aInfos.add(0, aInfo);
//				Collections.sort(aInfos, Global.sortByDate);
//				listAdapter.notifyDataSetChanged();
//				setAlarmEvent(bundle);
//				break;
//
//			default:
//				break;
//			}
//		} else if (requestCode == Global.REQUEST_ID_MODIFYACTIVITY) {
//			switch (resultCode) {
//			case RESULT_OK:
//				Bundle bundle = data.getExtras();
//				ActivityInfo aInfo = Global.getActivityInfo(bundle);
//				updateData(aInfo);
//				aInfos.set(data.getIntExtra("position", 0), aInfo);
//				listAdapter.notifyDataSetChanged();
//				setAlarmEvent(bundle);
//				break;
//
//			default:
//				break;
//			}
//		}
//
//		super.onActivityResult(requestCode, resultCode, data);
//	}

	private void initDataFromDB(ArrayList<ActivityInfo> list) {
		if (list == null)
			return;
		list.clear();
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cs;
		cs = db.query("pda", null, null, null, null, null, null);
		if (cs.moveToFirst()) {
			int nIndexOf_id = cs.getColumnIndex("id");
			int nIndexOf_date = cs.getColumnIndex("date");
			int nIndexOf_title = cs.getColumnIndex("title");
			int nIndexOf_content = cs.getColumnIndex("content");
			int nIndexOf_image_path = cs.getColumnIndex("image_path");
			int nIndexOf_sound_path = cs.getColumnIndex("sound_path");
			int nIndexOf_color = cs.getColumnIndex("color");
			do {
				int nId = cs.getInt(nIndexOf_id);
				Long lDate = cs.getLong(nIndexOf_date);
				String sTitle = cs.getString(nIndexOf_title);
				String sContent = cs.getString(nIndexOf_content);
				String sImagePath = cs.getString(nIndexOf_image_path);
				String sSoundPath = cs.getString(nIndexOf_sound_path);
				int color = cs.getInt(nIndexOf_color);

				ActivityInfo aInfo = new ActivityInfo(nId, sTitle, lDate,
						sContent, sImagePath, sSoundPath, color);
				list.add(0, aInfo);

			} while (cs.moveToNext());
		}
		cs.close();
		db.close();
		dbHelper.close();
		Collections.sort(list, Global.sortByDate);
	}

	private void insertData(ActivityInfo aInfo) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();

		int nId = aInfo.getId();
		Long lDate = aInfo.getDate();
		String sTitle = aInfo.getTitle();
		String sContent = aInfo.getContent();
		String sImagePath = aInfo.getImage();
		String sSoundPath = aInfo.getAudio();
		int color = aInfo.getColor();

		cv.put("id", nId);
		cv.put("date", lDate);
		cv.put("title", sTitle);
		cv.put("content", sContent);
		cv.put("image_path", sImagePath);
		cv.put("sound_path", sSoundPath);
		cv.put("color", color);
		db.insert(DatabaseHelper.TABLE_NAME, null, cv);
		cv.clear();

		db.close();
		dbHelper.close();
	}

	private void deleteData(ActivityInfo aInfo) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String where = "id=" + aInfo.getId();
		db.delete(DatabaseHelper.TABLE_NAME, where, null);
		db.close();
		dbHelper.close();
	}

	private void updateData(ActivityInfo aInfo) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();

		int nId = aInfo.getId();
		Long lDate = aInfo.getDate();
		String sTitle = aInfo.getTitle();
		String sContent = aInfo.getContent();
		String sImagePath = aInfo.getImage();
		String sSoundPath = aInfo.getAudio();
		int color = aInfo.getColor();

		// cv.put("id", nId);
		cv.put("date", lDate);
		cv.put("title", sTitle);
		cv.put("content", sContent);
		cv.put("image_path", sImagePath);
		cv.put("sound_path", sSoundPath);
		cv.put("color", color);

		String where = "id=" + nId;
		db.update(DatabaseHelper.TABLE_NAME, cv, where, null);
		cv.clear();

		db.close();
		dbHelper.close();
	}

	private void setAlarmEvent(Bundle bundle) {
		Intent alarmIntent = new Intent(this, alarmReceiver.class);

		alarmIntent.putExtras(bundle);
		int nId = bundle.getInt(DatabaseHelper.COLUMN_ID);
		long lDate = bundle.getLong(DatabaseHelper.COLUMN_DATE);
		Date date = new Date(lDate);
		date.setYear(date.getYear() - 1900);
		// lDate = date.getTime();

		PendingIntent sender = PendingIntent.getBroadcast(this, nId,
				alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

		alarmManager.set(AlarmManager.RTC_WAKEUP, lDate, sender);
		// Log.e("create", "event: " + String.valueOf(lDate));
		// Log.e("create", "currt: " +
		// String.valueOf(System.currentTimeMillis()));

	}

	private void cancelAlarmEvent(Bundle bundle) {
		Intent alarmIntent = new Intent(this, alarmReceiver.class);
		alarmIntent.putExtras(bundle);
		int nId = bundle.getInt(DatabaseHelper.COLUMN_ID);
		PendingIntent sender = PendingIntent.getBroadcast(this, nId,
				alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterContextMenuInfo info;

		try {
			info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		} catch (ClassCastException e) {
			Log.e("MENU ERROR", "bad menuInfo", e);
			return;
		}
		ActivityInfo aInfo = aInfos.get(info.position);

		menu.setHeaderTitle(aInfo.getTitle());
		menu.add(0, 0, 0, "View");
		menu.add(0, 1, 1, "Modify");
		menu.add(0, 2, 2, "Delete");

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info;
		try {

			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		} catch (ClassCastException e) {
			Log.e("MENU ERROR", "bad menuInfo", e);
			return false;
		}
		int position = info.position;
		ActivityInfo aInfo = aInfos.get(position);

		int id = item.getItemId();
		switch (id) {
		case 0:
			Intent i = new Intent();
			i.setClass(context, ViewActivity.class);
			i.putExtras(Global.getBundle(aInfo));
			startActivity(i);
			break;
		case 1:
			Intent intent = new Intent();
			intent.setClass(context, NewActivity.class);
			intent.putExtras(Global.getBundle(aInfo));
			intent.putExtra("position", position);

			startActivityForResult(intent, Global.REQUEST_ID_MODIFYACTIVITY);
			break;
		case 2:
			cancelAlarmEvent(Global.getBundle(aInfo));
			deleteData(aInfo);
			deleteFiles(aInfo);
			aInfos.remove(position);
			listAdapter.notifyDataSetChanged();
			break;
		default:
			break;
		}

		return super.onContextItemSelected(item);
	}

	private void deleteFiles(ActivityInfo aInfo) {
		File file = new File(aInfo.getImage());
		if (file.exists())
			file.delete();
		file = new File(aInfo.getAudio());
		if (file.exists())
			file.delete();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "List");
		menu.add(0, 1, 1, "Calendar View");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			// linearLayout_main.removeAllViews();
			// linearLayout_main.addView(lv_Activities);
			break;
		case 1:
			// linearLayout_main.removeAllViews();
			// DateWidget dateWidget = new DateWidget(this);
			// dateWidget.setOrientation(LinearLayout.VERTICAL);
			// linearLayout_main.addView(dateWidget, new LayoutParams(
			// LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			Intent intent = new Intent(this, CalendarActivity.class);
			startActivity(intent);

			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		Log.i("destroy", "called");
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

}